<?php

class User extends CActiveRecord
{
	const ADMIN_ID = 1;
	
	private static $_saltAddon = 'vasitcard';
	public $password_repeat;
	public $old_password;
	
	public $verifyCode;
	
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	public function tableName()
	{
		return '{{users}}';
	}
        
	public function rules()
	{
		return array(
			array('username, password, password_repeat, email', 'required', 'on' => 'admin'),
			array('isAdmin', 'numerical', 'integerOnly'=>true),
			array('username, password, salt, email', 'length', 'max'=>128),
			
			// password scenario
			array('password', 'compare', 'on' => 'admin',
				'message' => tt('Passwords are not equivalent! Try again.')),
			array('password', 'length', 'min' => 6, 'on' => 'admin',
				'tooShort' => tt('Password too short! Minimum allowed length is 6 chars.')
			),
			array('password_repeat', 'safe'),
			
			// email scenario
			array('email', 'email'),
			array('username, email', 'unique'),
			
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, username, password, email, isAdmin, active', 'safe', 'on'=>'search'),
			// update scenario
			array('username, email', 'required', 'on' => 'update'),
			array('password', 'compare', 'on' => 'update',
				'compareAttribute' => 'password_repeat',
				'allowEmpty' => true,
				'message' => tt('Passwords are not equivalent! Try again.')),
			
			// register scenario
			array('username, password, password_repeat, email', 'required', 'on' => 'register'),
			array('verifyCode', 'captcha', 'allowEmpty'=>!CCaptcha::checkRequirements(), 'on' => 'register'),
                    
                        // api scenario
			array('username, password, email', 'required', 'on' => 'api'),
			//array('verifyCode', 'captcha', 'allowEmpty'=>!CCaptcha::checkRequirements(), 'on' => 'register'),
			
		);
	}

	public function relations()
	{
		return array(
		);
	}

	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'active' => tt('Active'),
			'username' => tt('Username'),
			'password' => tt('Password'),
			'password_repeat' => tt('Repeat password'),
			'email' => tt('Email'),
			'creationDate' => tt('Registration Date'),
			'verifyCode'=>tt('Verification Code'),
		);
	}

	public function validatePassword($password) {	    
		return self::hashPassword($password, $this->salt) === $this->password;
	}
	
	public static function hashPassword($password, $salt) {
		return md5($salt . $password . $salt . self::$_saltAddon);
	}
	
	public static function generateSalt() {
		return uniqid('', true);
	}

	public function setPassword($password = null){
		$this->salt = self::generateSalt();
		if($password == null){
			$password = $this->password;
		}
		$this->password = md5($this->salt . $password . $this->salt . self::$_saltAddon);
	}
	
	public function setStatus()
	{
		$this->active = (param('registrationAdminApproveRequired')) ? 0 : 1;
	}
	
	public function randomString($length = 10){
		$chars = array_merge(range(0,9), range('a','z'), range('A','Z'));
		shuffle($chars);
		return implode(array_slice($chars, 0, $length));
	}

	public function search()
	{
		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('username',$this->username,true);
		$criteria->compare('email',$this->email,true);
		$criteria->compare('isAdmin',$this->isAdmin);
		$criteria->compare('active',$this->active);

		return new CActiveDataProvider(get_class($this), array(
			'criteria'=>$criteria,
		));
	}
	
	
	public function isUserExist($nickname, $email){
		$connection=Yii::app()->db;
		$sql = 'SELECT COUNT(*) as cnt FROM '.$this->tableName().' WHERE username="'.$nickname.'" OR email="'.$email.'"';
		$command = $connection->createCommand($sql);
		$dataReader = $command->query();
		$is_exist = 0;
		foreach($dataReader as $row) {
			if ($row['cnt'] > 0){
				$is_exist = 1;
				break;
			}
		}
		return $is_exist;
	}


	public function getUserByName($userName)
	{
		$command = Yii::app()->db->createCommand("SELECT * FROM ".$this->tableName()." WHERE username = :username");
		$command->bindParam(":username", $userName);
		
		return $command->queryRow();
	}
}